<?php

declare(strict_types=1);


namespace app\controller\mini;

use app\controller\admin\AdminBaseController;
use app\model\admin\Product;
use app\model\admin\ProductAttrValue;
use app\model\admin\ShippingTemp;
use app\model\admin\ShippingTempFree;
use app\model\admin\ShippingTempNoDe;
use app\model\admin\ShippingTempRegion;
use app\Request;
use app\model\admin\SysMember;
use app\model\mini\Address;
use app\model\mini\Cart;
use app\model\mini\MiniUser;
use app\model\mini\Order;
use app\model\mini\OrderItem;
use app\model\mini\OrderLog;
use app\queue\CloseOrder;
use app\service\OrderService;
use think\facade\Db;
use think\facade\Queue;

class OrderController extends AdminBaseController
{
    // 查看物流
    public function getLogistic(Request $request)
    {
        $id = input('id');
        $type = input('type');
        $params = $request->param();
        $user_id = $request->user_id;
        $express_no = "";
        $address = "";
        if ($type == "refund") {
            $orderItem = OrderItem::with(['order', 'refund' => function ($q) {
                $q->where('is_del', 0)->order('id', 'desc');
            }])->where([
                "user_id" => $user_id,
                "id" => $params['order_item_id'],
            ])->find();
            // var_dump($orderItem);
            $express_no = $orderItem->refund_express;
            $address = $orderItem->order->user_address;
        } else {
            $order = Order::with(['orderItem' => function ($q) {
                $q->with(['refund' => function ($q) {
                    $q->where('is_del', 0)->order('id', 'desc');
                }]);
            }])->where([
                "user_id" => $user_id,
                "id" => $id,
            ])->find();
            $address = $order->user_address;
            $express_no = $order->delivery_id;
        }


        // 查看物流
        $config = config('express');
        $data = [
            "NO" => $express_no,
            "TYPE" => "auto"
        ];
        $data_str = http_build_query($data);
        $headers = [
            'Authorization:APPCODE ' . $config['appcode']
        ];
        $return_str = $this->httpRequest($config['url'] . '?' . $data_str, 'GET', null, "", '', $headers);
        $return_arr = json_decode($return_str, true);
        storage_log("物流参数url:" . json_encode($config));
        storage_log("物流返回:" . $return_str);
        if ($return_arr['status'] == "200") {
            // 0在途中1揽件，货物已由快递公司揽收并且产生了第一条跟踪信息;2货物寄送过程出了问题:3签收，收件人已签收;4退签，即货物由于用户拒签、超区等原因退回，而且发件人已经签收:5派件，即快递正在进行同城派件;6退回，货物正处于退回发件人的途中
            foreach ($return_arr['list'] as $key => &$val) {
                $val['time_arr'] = explode(' ', $val['time']);
            }
            // if()
            $map = [
                0 => '运输中',
                1 => '已揽件',
                2 => '运输异常',
                3 => '已签收',
                4 => '已退签',
                5 => '同城派件',
                6 => '退回中',
            ];
            $return_arr['status'] = $map[$return_arr['state']];
            $return_arr['address'] = $address;
            return success($return_arr);
        } else {
            return error($return_arr['message']);
        }
    }
    // 确认订单 前端点击确认收货
    public function confirmOrder(Request $request)
    {
        $params = $request->param();
        $user_id = $request->user_id;
        $info = Order::with(['orderItem'])->where([
            'pay_status' => 1,
            'user_id' => $user_id,
        ])->find($params['id']);
        if ($info->order_status == 1) {
            $info->order_status = 2; //已收货，交易完成
            // $info->delivery_id = $params['delivery_id'];
            // $info->save();
            try {
                Db::transaction(function () use ($info) {
                    Db::table('user_order')->where('id', $info->id)->update([
                        "order_status" => 2
                    ]);
                    OrderLog::create([
                        "order_id" => $info->id,
                        "message" => "用户已点击确定收货"
                    ]);
                });
                // todo模版通知用户
                OrderService::handleCommission($params['id']);
            } catch (\Exception $e) {
                storage_log("confirmOrder" . $e->getMessage());
                return error($e->getMessage());
            }
            // 结算收益
            return success();
        } else {
            return error('当前订单不允许确认收货');
        }
    }
    // 订单再次发起付款
    public function orderPay(Request $request)
    {
        $id = input('id');
        $user_id = $request->user_id;
        $info = Order::where('pay_status', 0)->where([
            "id" => $id,
            "user_id" => $user_id,
        ])->find();
        if (!$info) {
            return error('记录不存在');
        }
        // 验证时间
        $end_pay_time =  strtotime($info->created_at) + $this->miniInfo['closeOrder'];
        if (time() > $end_pay_time) {
            // 超时了
            return error('该订单已超时');
        }
        $payRes = $this->getPayparams($info, $info->order_price);
        OrderLog::create([
            "order_id" => $info->id,
            "message" => "订单再次发起支付"
        ]);
        if ($payRes['code'] == 200) {
            return success([
                "order_id" => $info->id,
                "pay_params" => $payRes['payInfo']
            ]);
        } else {
            return error($payRes['msg']);
        }
    }
    public function canelOrder(Request $request)
    {
        $id = input('id');
        $user_id = $request->user_id;
        $info = Order::where('pay_status', 0)->where([
            "id" => $id,
            "user_id" => $user_id,
        ])->find();
        if ($info) {
            $info->pay_status = 2;
            $info->order_status = 4; //修改订单为交易失败
            $info->save();
            return success();
        } else {
            return error('修改失败');
        }
    }
    public function getOrderInfo(Request $request)
    {
        $id = input('id');
        $user_id = $request->user_id;
        $info = Order::with(['orderItem', 'orderItem.refund'])->where('user_id', $user_id)->where('id', $id)->find();
        $end_pay_time = date("Y-m-d H:i:s", strtotime($info->created_at) + $this->miniInfo['closeOrder']);
        $info->end_pay_time = $end_pay_time;
        $info->order_unpaid = "/static/order_unpaid.gif";
        $info->order_unsend = "/static/order_unsend.gif";
        $info->order_send = "/static/order_send.gif";
        $info->order_reply = "/static/order_reply.gif";
        // 

        return success($info);
    }
    public function getOrderList(Request $request)
    {
        $user_id = $request->user_id;
        $type = input('type');
        if ($type == -1) {
            // 查所有
            $list = Order::with(['orderItem'])
                ->where([
                    'user_id' => $user_id,
                ])->whereIn('pay_status', [0, 1]) //查询未支付和已支付的
                ->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        } else if ($type == 2) {
            // 待支付
            $list = Order::with(['orderItem'])
                ->where('user_id', $user_id)
                ->where('pay_status', 0)
                ->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        } else if ($type == 3) {
            // 查已完成
            $list = Order::with(['orderItem'])
                ->where('user_id', $user_id)
                ->where('order_status', 5)
                ->where('pay_status', 1)
                ->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        } else if ($type == 4) {
            // 待发货
            $list = Order::with(['orderItem'])
                ->where('user_id', $user_id)
                ->where('pay_status', 1)
                ->where('order_status', 0)->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        } else if ($type == 5) {
            // 因为退款导致交易失败
            $list = Order::with(['orderItem'])
                ->where('user_id', $user_id)->where('pay_status', 1)
                ->where('order_status', 4)->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        } else {
            $list = Order::with(['orderItem'])
                ->where('user_id', $user_id)
                ->where('order_status', $type)->order('id', 'desc')->paginate([
                    'list_rows' => $this->limit,
                    'page' => $this->page,
                    'var_page' => $this->pageVar
                ]);
        }
        // 查询
        $send_count = Order::where('user_id', $user_id)->where('order_status', 0)->count();
        $rece_count = Order::where('user_id', $user_id)->where('order_status', 1)->count();
        $pay_count = Order::where('user_id', $user_id)->where('pay_status', 0)->count();
        $succ_count = Order::where('user_id', $user_id)->where('order_status', 2)->count();
        // $all_count = $send_count + $rece_count + $pay_count;
        $all_count = Order::where('user_id', $user_id)->order('id', 'desc')->count();
        return success([
            'items' => $list->items(),
            'send_count' => $send_count,
            'succ_count' => $succ_count,
            'rece_count' => $rece_count,
            'pay_count' => $pay_count,
            'all_count' => $all_count,
            'pageSize' => $list->listRows(),
            'pageNum' => $list->currentPage(),
            'total' => $list->total(),
            'totalPage' => $list->lastPage(),
        ]);
    }
    // 预下单
    public function getPreOrderInfo(Request $request)
    {
        $cart_ids = input('cart_ids');
        $address_id = input('address_id');
        $user_id = $request->user_id;
        $addressInfo = null;
        if (!$address_id) {
            // 未传地址选择默认地址
            $addressInfo = Address::where([
                "user_id" => $user_id,
                "is_default" => 1,
            ])->find();
        } else {
            $addressInfo = Address::where([
                "user_id" => $user_id,

            ])->find($address_id);
        }
        // $list  = Product::with(['attr_value'])->whereIn('id', $product_ids)->select()->toArray();
        $list = Cart::with(['product'])->whereIn('id', $cart_ids)->select()->toArray();
        // var_dump(count($list));
        $total_price = 0; // 总价
        $newArr = [];
        foreach ($list as $key => &$val) {
            if ($val['spec_type'] == 1) {
                // 
                $product_val = ProductAttrValue::where([
                    "product_id" => $val['product_id'],
                    "sku" => $val['sku']
                ])->find();
                $val['price'] = $product_val->price;
                $val['image'] = $product_val->image;
                $val['goods_name'] = $val['product']['goods_name'];
            } else {
                // 单规格
                $val['price'] = $val['product']['price'];
                $val['image'] = $val['product']['image'];
                $val['goods_name'] = $val['product']['goods_name'];
            }
            $val['no_de'] = 0;   //默认送达
            $val['in_area'] = true; //默认在指定配送区域
            $val['is_buy'] = true; //默认可以购买
            // 选择了地址才计算运费
            if ($addressInfo) {
                // 是否包邮
                $province_id = $addressInfo->province_id;
                $city_id = $addressInfo->city_id;

                $is_postage = $val['product']['is_postage'];
                if ($val['product']['freight'] == 2) {
                    // 固定运费
                    $val['pay_postage'] = $val['product']['postage'];
                }
                if ($val['product']['freight'] == 3) {
                    // 运费模版
                    // $val['pay_postage'] = $val['product']['postage'];
                    $shipTemp = ShippingTemp::find($val['product']['temp_id']);
                    if ($shipTemp->no_delivery == 1) {
                        // 开启指定不送达
                        $tempNoDe = ShippingTempNoDe::where([
                            "temp_id" => $shipTemp->id,
                        ])->find();
                        // todo验证配送省份id是不是在限制内，不是指定区域不送达在计算运费
                        if ($tempNoDe) {
                            if ($tempNoDe->province_id) {
                                $no_province = explode(',', $tempNoDe->province_id);

                                if ($tempNoDe->city_id) {
                                    //指定城市不送达
                                    $no_city = explode(',', $tempNoDe->city_id);
                                    if (in_array($city_id, $no_city)) {
                                        $val['no_de'] = 1; //标记为不送达
                                    }
                                } else {
                                    // 未设置限制城市，只限制省份
                                    if (in_array($province_id, $no_province)) {
                                        $val['no_de'] = 1; //标记为不送达
                                    }
                                }
                            }
                        }
                    }

                    // 只配送指定区域，send_type 1 全国 2 指定区域
                    if ($shipTemp->send_type == 2) {
                        // 获取配送区域
                        $send_type_area = ShippingTempRegion::find($shipTemp->id);
                        // $province_id = $send_type_area->province_id;
                        // $city_id = $send_type_area->city_id;
                        if ($send_type_area) {
                            if ($send_type_area->province_id) {

                                $send_province_id = explode(',', $send_type_area->province_id);

                                if ($send_type_area->city_id) {
                                    // 配送指定城市
                                    $send_city_id = explode(',', $send_type_area->city_id);
                                    if (!in_array($city_id, $send_city_id)) {
                                        // 不在指定城市中，不送达
                                        $val['in_area'] = false;
                                    }
                                } else {
                                    // 只设置了省份,代表只送省份内的
                                    if (!in_array($province_id, $send_province_id)) {
                                        // 不在指定城市中，不送达
                                        $val['in_area'] = false;
                                    }
                                }
                            }
                        }
                    }
                    $shipTempType = $shipTemp->type;
                    // 计算运费：计件方式：1件数，2体积 3重量
                    $ship_free = ShippingTempFree::find($shipTemp->id);
                    if ($ship_free) {
                        // 配置了指定包邮
                        $free_num = $ship_free->number;
                        switch ($shipTempType) {
                            case 1:
                                # code...件数
                                $val['num'] - $free_num;
                                // break;
                            case 2:
                                # code...体积
                                break;
                            case 2:
                                # code...重量
                                break;

                            default:
                                # code...
                                break;
                        }
                    }


                    // // 
                    // $shipTempType = $shipTemp->type;

                    // // 获取商品的重量体积啊和件数在计算费用

                }
                if ($val['no_de'] == 1) {
                    // 商品不送达
                    $val['is_buy'] = false;
                }
                if ($val['in_area'] == false) {
                    // 商品不送达(地址不再指定送达区域内)
                    $val['is_buy'] = false;
                }
                // 计算总价
                if ($val['is_buy']) {
                    $total_price = bcadd(strval($total_price), bcadd(bcmul(strval($val['price']), strval($val['num']), 2), strval($val['pay_postage']), 2), 2);
                }
            } else {
                // $total_price = bcadd(strval($total_price), bcadd(bcmul(strval($val['price']), strval($val['num']), 2), strval($val['pay_postage']), 2), 2);
                $total_price = bcadd(strval($total_price), bcmul(strval($val['price']), strval($val['num']), 2), 2);
            }
        }

        return success([
            "address_info" => $addressInfo,
            "cart_list" => $list,
            "total_price" => $total_price
        ]);
    }
    // 下单
    public function createOrder(Request $request)
    {
        $cart_ids = input('cart_ids');
        $address_id = input('address_id');
        $user_id = $request->user_id;
        $remark = input('remark');
        $list = Cart::with(['product'])->whereIn('id', $cart_ids)->where('user_id', $user_id)->select()->toArray();
        $address = Address::find($address_id);
        $user = MiniUser::find($user_id);


        $province_id = $address->province_id;
        $city_id = $address->city_id;
        // 入库
        $order_id = null;
        $sum_price = 0;
        $sum_count = 0;
        Db::startTrans();
        try {
            $order = Order::create([
                "order_sn" => "MINI" . date("YmdH") . sprintf('%04d', $user_id) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)),
                // "total_num"=>count($list)
                "user_id" => $user_id,
                "operator_id" => $user->op_id,
                "user_remak" => $remark ?? '',
                "pay_status" => 0,
                "openid" => $user->openid,
                "order_status" => 0, //待发货
                "address_id" => $address->id,
                "user_phone" => $address->phone,
                "user_address" => $address->province . " " . $address->city . " " . $address->area . " " . $address->detail,
                "real_name" => $address->real_name,
            ]);
            $order_id = $order->id;
            foreach ($list as $key => &$val) {
                if ($val['product']['status'] == 0) {
                    // 未上架跳过
                    continue;
                }
                $sum_count += $val['num'];
                $product_val = [];
                if ($val['spec_type'] == 1) {
                    // 
                    $product_val = ProductAttrValue::where([
                        "product_id" => $val['product_id'],
                        "sku" => $val['sku']
                    ])->find();
                    $val['price'] = $product_val->price;
                    $val['cost'] = $product_val->cost;
                    $val['image'] = $product_val->image;
                    $val['goods_name'] = $val['product']['goods_name'];
                } else {
                    // 单规格
                    $val['price'] = $val['product']['price'];
                    $val['cost'] = $val['product']['cost'];
                    $val['image'] = $val['product']['image'];
                    $val['goods_name'] = $val['product']['goods_name'];
                }
                $val['no_de'] = 0;   //默认送达
                $val['in_area'] = true; //默认在指定配送区域
                $val['is_buy'] = true; //默认可以购买
                // 是否包邮
                $is_postage = $val['product']['is_postage'];
                if ($val['product']['freight'] == 2) {
                    // 固定运费
                    $val['pay_postage'] = $val['product']['postage'];
                }
                if ($val['product']['freight'] == 3) {
                    // 运费模版
                    $val['pay_postage'] = 0; //todo计算邮费
                    // $val['pay_postage'] = $val['product']['postage'];
                    $shipTemp = ShippingTemp::find($val['product']['temp_id']);
                    if ($shipTemp->no_delivery == 1) {
                        // 开启指定不送达
                        $tempNoDe = ShippingTempNoDe::where([
                            "temp_id" => $shipTemp->id,
                        ])->find();
                        // todo验证配送省份id是不是在限制内，不是指定区域不送达在计算运费
                        if ($tempNoDe) {
                            if ($tempNoDe->province_id) {
                                $no_province = explode(',', $tempNoDe->province_id);

                                if ($tempNoDe->city_id) {
                                    //指定城市不送达
                                    $no_city = explode(',', $tempNoDe->city_id);
                                    if (in_array($city_id, $no_city)) {
                                        $val['no_de'] = 1; //标记为不送达
                                    }
                                } else {
                                    // 未设置限制城市，只限制省份
                                    if (in_array($province_id, $no_province)) {
                                        $val['no_de'] = 1; //标记为不送达
                                    }
                                }
                            }
                        }
                        // 计算运费：计件方式：1件数，2体积3重量
                        // $shipTempType = $shipTemp->type;

                        // 获取商品的重量体积啊和件数在计算费用
                    }

                    // 只配送指定区域
                    // 只配送指定区域，send_type 1 全国 2 指定区域
                    if ($shipTemp->send_type == 2) {
                        // 获取配送区域
                        $send_type_area = ShippingTempRegion::find($shipTemp->id);
                        // $province_id = $send_type_area->province_id;
                        // $city_id = $send_type_area->city_id;
                        if ($send_type_area) {
                            if ($send_type_area->province_id) {

                                $send_province_id = explode(',', $send_type_area->province_id);

                                if ($send_type_area->city_id) {
                                    // 配送指定城市
                                    $send_city_id = explode(',', $send_type_area->city_id);
                                    if (!in_array($city_id, $send_city_id)) {
                                        // 不在指定城市中，不送达
                                        $val['in_area'] = false;
                                    }
                                } else {
                                    // 只设置了省份,代表只送省份内的
                                    if (!in_array($province_id, $send_province_id)) {
                                        // 不在指定城市中，不送达
                                        $val['in_area'] = false;
                                    }
                                }
                            }
                        }
                    }
                    $shipTempType = $shipTemp->type;
                    // 计算运费：计件方式：1件数，2体积 3重量
                    $ship_free = ShippingTempFree::find($shipTemp->id);
                    if ($ship_free) {
                        // 配置了指定包邮
                        $free_num = $ship_free->number;
                        switch ($shipTempType) {
                            case 1:
                                # code...件数
                                $val['num'] - $free_num;
                                // break;
                            case 2:
                                # code...体积
                                break;
                            case 2:
                                # code...重量
                                break;

                            default:
                                # code...
                                break;
                        }
                    }
                }
                if ($val['no_de'] == 1) {
                    // 商品不送达
                    $val['is_buy'] = false;
                }
                if ($val['in_area'] == false) {
                    // 商品不送达(地址不再指定送达区域内)
                    $val['is_buy'] = false;
                }
                // 计算总价
                if ($val['is_buy']) {
                    $sum_price = bcadd(strval($sum_price), bcadd(bcmul(strval($val['price']), strval($val['num']), 2), strval($val['pay_postage']), 2), 2);
                }

                $orderItem = [
                    "order_id" => $order->id,
                    "cate_id" => $val['product']['cate_id'],
                    "goods_id" => $val['product']['id'],
                    "order_status" => 0,
                    "goods_price" => $val['price'],
                    "goods_num" => $val['num'],
                    "user_id" => $user_id,
                    "operator_id" => $user->op_id,
                    "cost" => $val['cost'],
                    "user_phone" => $address->phone,
                    "user_address" => $address->province . " " . $address->city . " " . $address->area . " " . $address->detail,
                    "real_name" => $address->real_name,
                    "good_info" => json_encode($val['product']),
                    "spec_type" => $val['spec_type'],
                    "freight_price" => $val['pay_postage'],
                    "pay_id" => 0, //todo
                    "mark" => ""
                ];
                if ($val['spec_type'] == 1) {
                    // 多规格
                    $orderItem['sku'] = json_encode($product_val);
                }
                OrderItem::create($orderItem);
            }
            // 修改order
            Db::table('user_order')->where('id', $order->id)->update([
                "total_price" => $sum_price,
                "total_num" => $sum_count,
                "order_price" => $sum_price, //默认就是商品价格
            ]);
            // 添加订单日志
            OrderLog::create([
                "order_id" => $order->id,
                "message" => "订单生成"
            ]);
            Db::commit();
            // 删除用户购物车数据
            Cart::whereIn('id', $cart_ids)->delete();
            // todo超时未支付处理
            $data = [
                "order_id" => $order->id
            ];

            // 单位秒 5分钟
            storage_log("closeOrder:" . $this->miniInfo['closeOrder']);
            //
            $q_res = Queue::later($this->miniInfo['closeOrder'], CloseOrder::class, $data);
            if (!$q_res) {
                storage_log('超时订单推送队列失败');
            }
            // 返回支付参数
            $payRes = $this->getPayparams($order, $sum_price);
            if ($payRes['code'] == 200) {
                return success([
                    "order_id" => $order_id,
                    "pay_params" => $payRes['payInfo']
                ]);
            } else {
                return error($payRes['msg']);
            }
        } catch (\Exception $e) {
            Db::rollback();
            storage_log("createOrder" . $e->getMessage());
            return error($e->getMessage());
        }
        // return;
        // Db::transaction(function () use ($list, $user_id, $address, $remark) {
        //     $order = Order::create([
        //         "order_sn" => "MINI" . date("YmdH") . sprintf('%04d', $user_id) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)),
        //         // "total_num"=>count($list)
        //         "user_id" => $user_id,
        //         "user_remak" => $remark ?? '',
        //         "pay_status" => 0
        //     ]);
        //     $order_id = $order->id;
        //     foreach ($list as $key => &$val) {
        //         if ($val['product']['status'] == 0) {
        //             // 未上架跳过
        //             continue;
        //         }
        //         $product_val = [];
        //         if ($val['spec_type'] == 1) {
        //             // 
        //             $product_val = ProductAttrValue::where([
        //                 "product_id" => $val['product_id'],
        //                 "sku" => $val['sku']
        //             ])->find();
        //             $val['price'] = $product_val->price;
        //             $val['cost'] = $product_val->cost;
        //             $val['image'] = $product_val->image;
        //             $val['goods_name'] = $val['product']['goods_name'];
        //         } else {
        //             // 单规格
        //             $val['price'] = $val['product']['price'];
        //             $val['cost'] = $val['product']['cost'];
        //             $val['image'] = $val['product']['image'];
        //             $val['goods_name'] = $val['product']['goods_name'];
        //         }
        //         // 是否包邮
        //         $is_postage = $val['product']['is_postage'];
        //         if ($val['product']['freight'] == 2) {
        //             // 固定运费
        //             $val['pay_postage'] = $val['product']['postage'];
        //         }
        //         if ($val['product']['freight'] == 3) {
        //             // 运费模版
        //             $val['pay_postage'] = 0; //todo计算邮费
        //             // $val['pay_postage'] = $val['product']['postage'];
        //             $shipTemp = ShippingTemp::find($val['product']['temp_id']);
        //             if ($shipTemp->no_delivery == 1) {
        //                 // 开启指定不送达
        //                 $tempNoDe = ShippingTempNoDe::where([
        //                     "temp_id" => $shipTemp->id,
        //                 ])->find();
        //                 // todo验证配送省份id是不是在限制内，不是指定区域不送达在计算运费

        //                 // 计算运费：计件方式：1件数，2体积3重量
        //                 $shipTempType = $shipTemp->type;

        //                 // 获取商品的重量体积啊和件数在计算费用
        //             }
        //             // 只配送指定区域

        //         }
        //         $orderItem = [
        //             "order_id" => $order->id,
        //             "order_status" => 0,
        //             "goods_price" => $val['price'],
        //             "goods_num" => $val['num'],
        //             "user_id" => $user_id,
        //             "cost" => $val['cost'],
        //             "user_phone" => $address->phone,
        //             "user_address" => $address->province . " " . $address->city . " " . $address->area . " " . $address->detail,
        //             "real_name" => $address->real_name,
        //             "good_info" => json_encode($val['product']),
        //             "spec_type" => $val['spec_type'],
        //             "freight_price" => $val['pay_postage'],
        //             "pay_id" => 0, //todo
        //             "mark" => ""
        //         ];
        //         if ($val['spec_type'] == 1) {
        //             // 多规格
        //             $orderItem['sku'] = json_encode($product_val);
        //         }
        //         OrderItem::create($orderItem);
        //     }
        //     // 添加订单日志
        //     OrderLog::create([
        //         "order_id" => $order->id,
        //         "message" => "订单生成"
        //     ]);
        //     return success($order_id);
        // });
    }
    public function getPayparams($order, $order_price)
    {
        // 默认微信支付
        $data = [
            "code" => 200,
            "msg" => "",
            "payInfo" => []
        ];
        // 测试价格
        // $order_price = "0.01";
        $paytime = time();
        $order_data = [
            'body' => "购买商品",
            'out_trade_no' => $order->order_sn,
            'total_fee' => floatval(bcmul(strval($order_price), "100", 2)),
            'notify_url' => $this->miniInfo['callback_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $order->openid,
        ];
        storage_log("order_price:" . $order_price);
        storage_log("支付请求参数:" . json_encode($order_data));
        $result = $this->payApp->order->unify($order_data);
        storage_log("微信支付请求返回:" . json_encode($result));
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $nonce_str = $result['nonce_str'];
            $prepay_id = $result['prepay_id'];
            $appid = $this->miniInfo['appid'];
            $key = $this->miniInfo['key'];
            $paySign   = md5("appId={$appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$key}");
            // 返回给小程序
            $res              = [];
            $res['nonceStr']  = $nonce_str;
            $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
            $res['package']   = "prepay_id=" . $prepay_id;
            $res['paySign']   = $paySign;
            $res['signType']  = 'MD5';
            // return success(["data" => $res]);
            $data['payInfo'] = $res;
            $data['code'] = 200;
        } else {
            // return null;
            $data['code'] = 500;
            $data['msg'] = "微信支付参数获取失败,原因：" . $result['return_msg'] ?? $result['err_code_des'] ?? '';

            // return error($result['err_code_des']);
        }
        return $data;
    }

    // public function getExpress(Request $request)
    // {
    //     $id = input('id');
    //     $order = Order::where([
    //         "user_id" => $user_id,
    //         "id" => $id,
    //     ])->find();
    //     return;
    // }
}
